package interceptor

import (
	"context"

	"zerorpc/pkg/errorx"

	"github.com/zeromicro/go-zero/core/logx"

	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// LoggerInterceptor 拦截rpc请求结果，如果出错并且是自定义错误类型则将自定义错误类型转换成grpc错误类型
func LoggerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	resp, err = handler(ctx, req)
	if err != nil {
		// 打印错误日志
		logx.WithContext(ctx).Errorf("[RPC-SRV-ERR] method:%s, req:%+v, err:%+v", info.FullMethod, req, err)

		// 转换错误类型
		causeErr := errors.Cause(err)
		if e, ok := causeErr.(*errorx.Error); ok {
			err = status.Error(codes.Code(e.GetCode()), e.GetMsg())
		}
	} else {
		logx.WithContext(ctx).Infof("[RPC-SRV-INFO] method:%s, req:%+v, reply:%v", info.FullMethod, req, resp)
	}
	return resp, err
}
